package com.example.blog.controller;

import com.example.blog.entity.User;
import com.example.blog.repository.LikesRepository;
import com.example.blog.Service.LikesService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.example.blog.entity.likes;

import java.util.Map;
@Slf4j
@Controller
@RequestMapping("/articlesLike")
public class LikesCtr {

    @Autowired
    private LikesService likesService;
    @Autowired
    private LikesRepository likesRepository;

    @RequestMapping(value = "/like")
    public ResponseEntity<?> likeArticle(@RequestParam("articleId") Integer articleId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(articleId==null){System.out.println("未找到");
        }
        System.out.println(">>>>>>>>>>>>>>articleId:" + articleId);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("success", false, "message", "用户未登录"));
        }
        try {
            likes existingLike = likesRepository.findByArticleIdAndUserId(articleId, user.getId());
            boolean liked = existingLike != null && existingLike.getStatus() == 1;
            if (liked) {
                likesService.unlikeArticle(articleId, user.getId());
            } else {
                likesService.likeArticle(articleId, user.getId());
            }
            System.out.println("liked>>>>>>>>>>>>:" + liked);
            return ResponseEntity.ok().body((Map.of("success", true, "liked", liked)));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("err:" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("success", false, "message", "操作失败"));
        }
    }
}